//dva model
// request 是 demo 项目脚手架中提供的一个做 http 请求的方法，
//是对于 fetch 的封装，返回 Promise
import request from '../util/request';
import { message } from 'antd';

const delay = (millisecond) => {
  return new Promise((resolve) => {
    setTimeout(resolve, millisecond);
  });
};

export default {
  namespace: 'puzzle-card',
  state: {
    data: [],
    counter: 100,
  },
  effects: {
    *queryInitCard(_, sagaEffects) {
      const { call, put } = sagaEffects;
      const endPointURI = '/dev/random_joke';
      // const endPointURI = '/dev/random_joke_e';// mock error
      try { // 加入 try catch 捕获抛错
        const puzzle = yield call(request, endPointURI);
        yield put({ type: 'addNewCard', payload: puzzle });

        yield call(delay, 250);

        const puzzle2 = yield call(request, endPointURI);
        yield put({ type: 'addNewCard', payload: puzzle2 });

        yield call(delay, 250);

        const puzzle3 = yield call(request, endPointURI);
        yield put({ type: 'addNewCard', payload: puzzle3 });

        yield call(delay, 250);

        const puzzle4 = yield call(request, endPointURI);
        yield put({ type: 'addNewCard', payload: puzzle4 });
      } catch (e) {
        message.error('数据获取失败'); // 打印错误信息
      }
    }
  },
  reducers: {
    addNewCard(state, { payload: newCard }) {
      const nextCounter = state.counter + 1;
      const newCardWithId = { ...newCard, id: nextCounter };
      const nextData = state.data.concat(newCardWithId);
      return {
        data: nextData,
        counter: nextCounter,
      };
    },
    initData(state) {
      return {
        data: [],
        counter: 0,
      };
    }
  }
};